<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本信息</span>
      </div>
      <div class="text item">
        <el-form ref="postForm" :model="postForm" :rules="rules" label-width="120px" label-position="right">
          <el-form-item label="用户名" prop="user_name">
            <el-input v-model.trim="postForm.user_name" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="密码" prop="user_password">
            <el-input v-model="postForm.user_password" type="password" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realname">
            <el-input v-model.trim="postForm.realname" style="width: 300px"/>
          </el-form-item>
          <el-form-item label="负责楼栋">
            <el-input v-model.trim="postForm.house" readonly style="width: 300px"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="box-card" style="margin: 20px 0px;">
      <div slot="header" class="clearfix">
        <span>楼栋公告</span>
      </div>
      <div class="text item">
        <div class="filter-container">
          <el-button type="primary" class="filter-item" @click="handleCreate">添加</el-button>
          <el-button type="danger" class="filter-item" @click="handleBatchDel">批量删除</el-button>
        </div>
        <el-table v-loading="listLoading" ref="multipleTable" :data="list" element-loading-text="Loading" border highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column type="selection"/>
          <el-table-column label="ID">
            <template slot-scope="scope">{{ scope.row.id }}</template>
          </el-table-column>
          <el-table-column label="标题">
            <template slot-scope="scope">{{ scope.row.title }}</template>
          </el-table-column>
          <el-table-column label="图片">
            <template slot-scope="scope">
              <img :src="scope.row.image_id" style="max-width: 100%;max-height: 100%;">
            </template>
          </el-table-column>
          <el-table-column label="是否显示">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.is_show" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949" @change="handleSwitch(scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleUpdate(scope.row.id)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="adsData"/>
        <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogStatus]">
          <el-form ref="dataForm" :rules="ads_rules" :model="temp" label-position="left" label-width="120px" style="width: 800px; margin-left:50px;">
            <el-form-item label="标题：" prop="title">
              <el-input v-model="temp.title" style="width: 300px"/>
            </el-form-item>
            <el-form-item label="图片：">
              <Upload v-model="temp.image_id" :imagelist="image_list"/>
            </el-form-item>
            <el-form-item label="是否显示：" prop="is_show">
              <el-switch v-model="temp.is_show" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveData">确定</el-button>
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getUserInfo, saveUser } from '@/api/admin'
import { getList, detail, save, del, changeStatus } from '@/api/ads'
import Upload from '@/components/Upload/chunkImg'
import Pagination from '@/components/Pagination'
export default {
  name: 'Index',
  components: { Upload, Pagination },
  data() {
    const checkPassword = (rules, value, callback) => {
      if (value == '') { // 未作改动
        callback()
      } else if (value.length <= 4) {
        console.log(value)
        callback(new Error('密码长度不小于5位'))
      } else {
        callback()
      }
    }
    return {
      postForm: {
        user_name: '',
        user_password: '',
        realname: ''
      },
      rules: {
        user_name: [{ required: true, message: '用户名不能为空', trigger: 'change' }],
        user_password: [{ validator: checkPassword, trigger: 'change' }],
        realname: [{ required: true, message: '真实姓名不能为空', trigger: 'change' }]
      },
      ads_rules: {
        title: [{ required: true, message: '标题必填', trigger: 'change' }],
        is_show: [{ required: true, message: '请选择是否显示', trigger: 'change' }]
      },
      listLoading: true,
      dialogVisible: false,
      temp: {
        id: undefined,
        title: '',
        image_id: '',
        is_show: 1
      },
      list: [],
      textMap: {
        'create': '添加',
        'update': '编辑'
      },
      dialogStatus: '',
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      image_list: [],
      multipleSelection: [],
      delArr: []
    }
  },
  created() {
    this.fetchData()
    this.adsData()
  },
  methods: {
    fetchData() {
      getUserInfo().then(res => {
        this.postForm.user_name = res.data.user_name
        this.postForm.realname = res.data.realname
        this.postForm.house = res.data.house
      })
      this.$nextTick(() => {
        this.$refs['postForm'].clearValidate()
      })
    },
    onSubmit() {
      // 密码不能用空格做密码
      if (this.postForm.user_password.length > 0 && this.postForm.user_password.trim() == '') {
        this.$message.error('不能使用空格做密码')
        return
      }
      this.$refs['postForm'].validate(valid => {
        if (valid) {
          saveUser(this.postForm).then(res => {
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          }).catch(() => {})
        }
      })
    },
    adsData() {
      getList(this.listQuery).then(res => {
        this.list = res.data.list
        this.total = res.data.total
        this.listLoading = false
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        image_id: '',
        is_show: 1
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(id) {
      this.resetTemp()
      this.dialogStatus = 'update'
      detail({ id }).then(res => {
        this.temp = res.data.detail
        this.temp.image_id = res.data.detail.image_id.toString()
        this.image_list = res.data.image_list
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.adsData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del({ id: id }).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.adsData()
        })
      }).catch(() => {
        this.$message({
          message: '取消删除',
          type: 'info'
        })
      })
    },
    handleBatchDel() {
      this.delArr = []
      for (const item of this.multipleSelection) {
        this.delArr.push(item.id)
      }
      this.$confirm('删除不可恢复，是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        if (this.delArr.length > 0) {
          del({ id: this.delArr }).then(response => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.adsData()
          })
        } else {
          this.$notify({
            message: '您尚未做批量选择',
            type: 'info',
            duration: 2000
          })
        }
      }).catch(() => {
        this.$refs.multipleTable.clearSelection()
        this.$message({
          type: 'info',
          message: '已取消批量删除'
        })
      })
    },
    handleSwitch(row) {
      const data = { id: row.id, is_show: row.is_show }
      this.$confirm('是否改变状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeStatus(data).then(response => {
          this.$notify({
            title: '成功',
            message: '状态修改成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        row.is_show = ~~!row.is_show
      })
    },
    saveData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          save(this.temp).then(res => {
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
            this.dialogVisible = false
            this.adsData()
          })
        }
      })
    }
  }
}
</script>

<style scoped>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 100%;
  }
</style>
